// pages/post/detail.js
const app = getApp()

Page({
  data: {
    post: null,
    likedUsers: [],
    comments: [],
    commentText: '',
    isFollowing: false
  },

  onLoad(options) {
    const postId = options.postId;
    this.loadPostDetail(postId);
  },

  // 加载动态详情
  loadPostDetail(postId) {
    // 模拟数据 - 从广场页面获取对应的动态数据
    const mockPosts = this.getMockPosts();
    const post = mockPosts.find(p => p.id === postId);
    
    if (post) {
      // 生成点赞用户数据
      const likedUsers = this.generateLikedUsers(post.likes);
      // 生成评论数据
      const comments = this.generateComments(post.comments);
      
      this.setData({
        post: post,
        likedUsers: likedUsers,
        comments: comments
      });
    } else {
      // 如果没有找到动态，显示错误
      wx.showToast({
        title: '动态不存在',
        icon: 'error'
      });
      setTimeout(() => {
        wx.navigateBack();
      }, 1500);
    }
  },

  // 获取模拟动态数据
  getMockPosts() {
    return [
      {
        id: '3001',
        user: {
          id: '1001',
          nickname: '小可爱',
          avatar_url: '/images/default-avatar.png',
          gender: 'female',
          birth_year: 2001,
          city: '杭州',
          education: '本科',
          major: '艺术设计',
          verified: true
        },
        content: '今天去了西湖，风景真的太美了！有没有小伙伴也喜欢旅游的？可以一起组队呀～',
        images: [
          'https://images.unsplash.com/photo-1542662565-7e4b66bae529?w=400&h=300&fit=crop',
          'https://images.unsplash.com/photo-1512453979798-5ea266f8880c?w=400&h=300&fit=crop',
          'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?w=400&h=300&fit=crop'
        ],
        likes: 128,
        comments: 45,
        shares: 12,
        is_liked: false,
        create_time: '2024-10-08 14:30',
        tags: ['旅行', '杭州', '西湖']
      },
      {
        id: '3002',
        user: {
          id: '1002',
          nickname: '阳光男孩',
          avatar_url: '/images/default-avatar.png',
          gender: 'male',
          birth_year: 1995,
          city: '上海',
          education: '硕士',
          major: '计算机科学',
          verified: true
        },
        content: '周末篮球局，有一起的吗？在徐家汇体育公园，新手老手都欢迎！',
        images: [
          'https://images.unsplash.com/photo-1546519638-68e109498ffc?w=400&h=300&fit=crop',
          'https://images.unsplash.com/photo-1519861155730-0a84f4e0b7e5?w=400&h=300&fit=crop'
        ],
        likes: 89,
        comments: 23,
        shares: 5,
        is_liked: true,
        create_time: '2024-10-08 12:15',
        tags: ['运动', '篮球', '上海']
      }
    ];
  },

  // 生成点赞用户数据
  generateLikedUsers(likeCount) {
    const mockUsers = [
      {
        id: 'user1',
        nickname: '小明',
        avatar_url: '/images/default-avatar.png'
      },
      {
        id: 'user2',
        nickname: '小红',
        avatar_url: '/images/default-avatar.png'
      },
      {
        id: 'user3',
        nickname: '小刚',
        avatar_url: '/images/default-avatar.png'
      }
    ];
    
    // 根据点赞数量返回前几个用户
    return mockUsers.slice(0, Math.min(likeCount, 3));
  },

  // 生成评论数据
  generateComments(commentCount) {
    const mockComments = [
      {
        id: 'comment1',
        user: {
          id: 'user4',
          nickname: '旅行达人',
          avatar_url: '/images/default-avatar.png'
        },
        content: '西湖真的很美！我也经常去，下次可以一起呀～',
        likes: 12,
        create_time: '10-08 15:20',
        showReplies: false,
        replies: [
          {
            id: 'reply1',
            user: {
              id: 'user9',
              nickname: '小可爱',
              avatar_url: '/images/default-avatar.png'
            },
            content: '好呀好呀！我下周末还想去，一起吗？',
            likes: 3,
            create_time: '10-08 16:30'
          },
          {
            id: 'reply2',
            user: {
              id: 'user10',
              nickname: '摄影爱好者',
              avatar_url: '/images/default-avatar.png'
            },
            content: '我也想去！可以一起拍照！',
            likes: 2,
            create_time: '10-08 17:15'
          }
        ]
      },
      {
        id: 'comment2',
        user: {
          id: 'user5',
          nickname: '摄影爱好者',
          avatar_url: '/images/default-avatar.png'
        },
        content: '照片拍得真好看！构图和光线都很棒！',
        likes: 8,
        create_time: '10-08 16:45',
        showReplies: false,
        replies: [
          {
            id: 'reply3',
            user: {
              id: 'user11',
              nickname: '小可爱',
              avatar_url: '/images/default-avatar.png'
            },
            content: '谢谢夸奖！我也在学习摄影呢～',
            likes: 1,
            create_time: '10-08 17:30'
          }
        ]
      },
      {
        id: 'comment3',
        user: {
          id: 'user6',
          nickname: '杭州本地人',
          avatar_url: '/images/default-avatar.png'
        },
        content: '欢迎来杭州玩！推荐你去灵隐寺和龙井村，也很不错！',
        likes: 15,
        create_time: '10-08 17:30',
        showReplies: false,
        replies: []
      },
      {
        id: 'comment4',
        user: {
          id: 'user7',
          nickname: '美食探索家',
          avatar_url: '/images/default-avatar.png'
        },
        content: '西湖边的餐厅也很不错，推荐楼外楼！',
        likes: 6,
        create_time: '10-08 18:15',
        showReplies: false,
        replies: []
      },
      {
        id: 'comment5',
        user: {
          id: 'user8',
          nickname: '户外运动爱好者',
          avatar_url: '/images/default-avatar.png'
        },
        content: '西湖边的骑行路线也很棒，可以租个自行车环湖！',
        likes: 9,
        create_time: '10-08 19:00',
        showReplies: false,
        replies: []
      }
    ];
    
    // 根据评论数量返回前几个评论
    return mockComments.slice(0, Math.min(commentCount, 5));
  },

  // 关注/取消关注
  toggleFollow() {
    const newFollowingStatus = !this.data.isFollowing;
    this.setData({
      isFollowing: newFollowingStatus
    });
    
    wx.showToast({
      title: newFollowingStatus ? '关注成功' : '已取消关注',
      icon: 'success'
    });
  },

  // 返回上一页
  goBack() {
    wx.navigateBack();
  },

  // 点赞/取消点赞
  toggleLike() {
    const post = this.data.post;
    const newLikeStatus = !post.is_liked;
    const newLikes = newLikeStatus ? post.likes + 1 : post.likes - 1;
    
    // 更新点赞用户数据
    let newLikedUsers = [...this.data.likedUsers];
    if (newLikeStatus) {
      // 添加当前用户到点赞列表
      const currentUser = {
        id: 'current_user',
        nickname: '我',
        avatar_url: '/images/default-avatar.png'
      };
      newLikedUsers = [currentUser, ...newLikedUsers].slice(0, 3);
    } else {
      // 从点赞列表中移除当前用户
      newLikedUsers = newLikedUsers.filter(user => user.id !== 'current_user');
    }
    
    // 更新数据
    this.setData({
      post: {
        ...post,
        is_liked: newLikeStatus,
        likes: newLikes
      },
      likedUsers: newLikedUsers
    });
  },

  // 分享
  sharePost() {
    wx.showShareMenu({
      withShareTicket: true
    });
  },

  // 聚焦评论输入框
  focusComment() {
    // 这里可以添加聚焦输入框的逻辑
    console.log('聚焦评论输入框');
  },

  // 评论输入
  onCommentInput(e) {
    this.setData({
      commentText: e.detail.value
    });
  },

  // 提交评论
  submitComment() {
    if (!this.data.commentText.trim()) {
      return;
    }
    
    // 创建新评论
    const newComment = {
      id: 'comment_' + Date.now(),
      user: {
        id: 'current_user',
        nickname: '我',
        avatar_url: '/images/default-avatar.png'
      },
      content: this.data.commentText,
      likes: 0,
      create_time: this.formatTime(new Date())
    };
    
    // 更新评论列表
    const comments = [newComment, ...this.data.comments];
    const post = this.data.post;
    const newComments = post.comments + 1;
    
    this.setData({
      post: {
        ...post,
        comments: newComments
      },
      comments: comments,
      commentText: ''
    });
    
    wx.showToast({
      title: '评论成功',
      icon: 'success'
    });
  },

  // 点赞评论
  likeComment(e) {
    const commentId = e.currentTarget.dataset.commentId;
    const comments = this.data.comments.map(comment => {
      if (comment.id === commentId) {
        return {
          ...comment,
          likes: comment.likes + 1
        };
      }
      return comment;
    });
    
    this.setData({ comments });
    
    wx.showToast({
      title: '点赞成功',
      icon: 'success'
    });
  },

  // 回复评论
  replyComment(e) {
    const commentId = e.currentTarget.dataset.commentId;
    const comment = this.data.comments.find(c => c.id === commentId);
    
    if (comment) {
      this.setData({
        commentText: `回复 ${comment.user.nickname}: `
      });
    }
  },

  // 点赞回复
  likeReply(e) {
    const commentId = e.currentTarget.dataset.commentId;
    const replyId = e.currentTarget.dataset.replyId;
    
    const comments = this.data.comments.map(comment => {
      if (comment.id === commentId && comment.replies) {
        const updatedReplies = comment.replies.map(reply => {
          if (reply.id === replyId) {
            return {
              ...reply,
              likes: reply.likes + 1
            };
          }
          return reply;
        });
        return {
          ...comment,
          replies: updatedReplies
        };
      }
      return comment;
    });
    
    this.setData({ comments });
    
    wx.showToast({
      title: '点赞成功',
      icon: 'success'
    });
  },

  // 切换回复显示/隐藏
  toggleReplies(e) {
    const commentId = e.currentTarget.dataset.commentId;
    const comments = this.data.comments.map(comment => {
      if (comment.id === commentId) {
        return {
          ...comment,
          showReplies: !comment.showReplies
        };
      }
      return comment;
    });
    
    this.setData({ comments });
  },

  // 回复回复
  replyToReply(e) {
    const commentId = e.currentTarget.dataset.commentId;
    const replyId = e.currentTarget.dataset.replyId;
    const userName = e.currentTarget.dataset.userName;
    
    this.setData({
      commentText: `回复 ${userName}: `
    });
  },

  // 格式化时间
  formatTime(date) {
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${month}-${day} ${hours}:${minutes}`;
  },

  // 图片加载错误处理
  onImageError(e) {
    console.log('图片加载失败:', e.detail.errMsg);
  }
});
